import React, { memo, useReducer } from 'react'

const App = memo(() => {
  // 用户给useReducer()提供reducer函数，用于操作数据的变化 这个reducer函数必须返回一个新的状态
  const reducer = (state, action) => {
    switch (action.type) {
      case 'increment':
        return {...state, count: state.count + 1}
      case 'decrement':
        return {...state, count: state.count - 1}
      default:
        return state
    }
  }
  const [state, dispatch] = useReducer(reducer,{count: 50})
  // useReducer() 返回一个状态和一个dispatch函数，dispatch函数用于触发reducer函数，从而改变状态
  // useReducer() 的第二个参数是初始状态
  return (
    <div>
      <h3>counter: {state.count}</h3>
      <button onClick={() => dispatch({type: 'increment'})}>+1</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-1</button>
    </div>
  )
})

export default App